﻿/*
* This software is licensed under the GNU General Public License, version 2
* You may copy, distribute and modify the software as long as you track changes/dates of in source files and keep all modifications under GPL. You can distribute your application using a GPL library commercially, but you must also provide the source code.

* DNNspot Software (http://www.dnnspot.com)
* Copyright (C) 2013 Atriage Software LLC
* Authors: Kevin Southworth, Matthew Hall, Ryan Doom

* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.

* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.

* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

* Full license viewable here: http://www.gnu.org/licenses/gpl-2.0.txt
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Security.Membership;
using DotNetNuke.Entities.Users;
using System.Collections;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security;
using DotNetNuke.Entities.Modules.Actions;

namespace DNNspot_CustomLogin
{
    public partial class Default : PortalModuleBase
    {
        SettingsHelper settingsHelper = new SettingsHelper();

       

        protected void Page_Load(object sender, EventArgs e)
        {
            ConfigureDefaults();


            if (UserId > 0)
            {                
                GenerateLoggedIn();
            }
            else  //NOT LOGGED IN
            {
                if (!IsPostBack)
                {
                    GenerateLogin();
                }
            }

            DebugOutput.Visible = false;
        }

        void GenerateLogin()
        {
            GenerateLogin("");
        }

        void GenerateLogin(string ErrorMessage)
        {
            String Template;
            String LoginText;

            LoginText = settingsHelper.LoginButtonText;
            Template = settingsHelper.LoginTemplate;

            Template = Template.Replace("[USERNAME]", "<input type=\"text\" id=\"DNNspotUserName" + ModuleId.ToString() + "\" name=\"DNNspotUserName" + ModuleId.ToString() + "\" class=\"DNNspotUserName\" />");
            Template = Template.Replace("[PASSWORD]", "<input type=\"password\" id=\"DNNspotPassword" + ModuleId.ToString() + "\" name=\"DNNspotPassword" + ModuleId.ToString() + "\" class=\"DNNspotPassword\" />");
            Template = Template.Replace("[ERRORMESSAGE]", ErrorMessage);
            Template = Template.Replace("[REMEMBERME]", "<input type=\"checkbox\" id=\"DNNspotRememberMe" + ModuleId.ToString() + "\" name=\"DNNspotRememberMe" + ModuleId.ToString() + "\" class=\"DNNspotRememberMe\" />");


            string registerlink = "";
            if (PortalSettings.UserId != -1)
                registerlink = DotNetNuke.Common.Globals.NavigateURL(PortalSettings.UserTabId,"");
            else
                registerlink = DotNetNuke.Common.Globals.NavigateURL(PortalSettings.ActiveTab.TabID, "Register");

            string forgotlink = DotNetNuke.Common.Globals.NavigateURL(PortalSettings.ActiveTab.TabID,"SendPassword");

            

            Template = Template.Replace("[REGISTER]", "<a href=\""+registerlink+"\" class=\"DNNspotRegisterLink\">");
            Template = Template.Replace("[/REGISTER]", "</a>");

            Template = Template.Replace("[FORGOTPASSWORD]", "<a href=\""+forgotlink+"\" class=\"DNNspotForgotLink\">");
            Template = Template.Replace("[/FORGOTPASSWORD]", "</a>");


            string TopOutput = Template;
            string BottomOutput = "";
            int loginlinkpos = Template.IndexOf("[LOGINLINKBUTTON]");
            int loginbuttonpos = Template.IndexOf("[LOGINBUTTON]");
            int loginimagebuttonpos = Template.IndexOf("[LOGINIMAGEBUTTON]");
            if (loginlinkpos > 0)
            {
                TopOutput = Template.Substring(0,loginlinkpos);
                BottomOutput = Template.Substring(loginlinkpos+17);
                LoginLink.Visible = true;
                LoginLink.Text = LoginText;
            }
            else if (loginbuttonpos > 0)
            {
                TopOutput = Template.Substring(0, loginbuttonpos);
                BottomOutput = Template.Substring(loginbuttonpos + 13);
                LoginButton.Visible = true;
                LoginButton.Text = LoginText;
            }
            else if (loginimagebuttonpos > 0)
            {
                TopOutput = Template.Substring(0, loginimagebuttonpos);
                BottomOutput = Template.Substring(loginimagebuttonpos + 18);
                LoginImageButton.ImageUrl = settingsHelper.LoginButtonImageUrl;

                LoginImageButton.Style.Add("width", settingsHelper.LoginButtonImageWidth + "px");
                LoginImageButton.Style.Add("height", settingsHelper.LoginButtonImageHeight + "px");
                LoginImageButton.Visible = true;
            }

            if (Request.QueryString["ReturnUrl"] != null)
            {
                BottomOutput += "<input type=\"hidden\" value=\""+Request.QueryString["ReturnUrl"]+"\" name=\"LoginReturnURL\" id=\"LoginReturnURL\"/>";
            }
           


            OutputBeforeLogin.Text = TopOutput;
            OutputAfterLogin.Text = BottomOutput;
                                    
        }
        void GenerateLoggedIn()
        {
            String Template;

            Template = settingsHelper.LoggedInTemplate;
            Template = Template.Replace("[USERNAME]", UserInfo.Username);
            Template = Template.Replace("[FIRSTNAME]", UserInfo.FirstName);
            Template = Template.Replace("[LASTNAME]", UserInfo.LastName);
            Template = Template.Replace("[DISPLAYNAME]", UserInfo.DisplayName);
            Template = Template.Replace("[USERID]", UserInfo.UserID.ToString());
            Template = Template.Replace("[EMAIL]", UserInfo.Email.ToString());


            //NOT CORRECT
            string settingslink = "";
            if (PortalSettings.UserTabId != -1)
                settingslink = DotNetNuke.Common.Globals.NavigateURL(PortalSettings.UserTabId, "");
            else
                settingslink = DotNetNuke.Common.Globals.NavigateURL(PortalSettings.ActiveTab.TabID, "Register");

            Template = Template.Replace("[SETTINGS]", "<a href=\"" + settingslink + "\" class=\"DNNspotSettingsLink\">");
            Template = Template.Replace("[/SETTINGS]", "</a>");

            Template = Template.Replace("[LOGOUT]", "<a href=\"http://" + PortalSettings.PortalAlias.HTTPAlias + "/Logoff.aspx" +  "\" class=\"DNNspotLogoutLink\" >");
            Template = Template.Replace("[/LOGOUT]", "</a>");

            
            // - logoff.aspx
            // - 

            //TODO: Need to generate logout link
            //TODO: Need to generate edit profile / settings link
            OutputBeforeLogin.Text = Template;
        }
        UserLoginStatus UserLogin(string username, string password,bool rememberme)
        {
            DebugOutput.Text += "USERNAME:"+username + " " + password;
            
            UserLoginStatus userloginstatus = new UserLoginStatus();                        
            UserInfo userinfo=UserController.UserLogin(PortalId, username, password, "", PortalSettings.PortalName, HttpContext.Current.Request.UserHostAddress,ref userloginstatus, rememberme);
            return userloginstatus;
                        
        }
        void RedirectLogin(string username)
        {
            DebugOutput.Text += "Login Good Go somewhere";

            UserInfo user = UserController.GetUserByName(PortalId, username);

            if (Request.Params["LoginReturnURL"] != null)
            {
                Response.Redirect((string)Request.Params["LoginReturnURL"]);
            }

           
                if (settingsHelper.Redirect1.Length > 0)
                {
                    foreach (string role in user.Roles)
                    {
                        if (role == settingsHelper.Role1)
                        {
                            Response.Redirect(settingsHelper.Redirect1);
                        }
                    }
                }

                if (settingsHelper.Redirect2.Length > 0)
                {
                    foreach (string role in user.Roles)
                    {
                        if (role == settingsHelper.Role2)
                        {
                            Response.Redirect(settingsHelper.Redirect2);
                        }
                    }
                }

                if (settingsHelper.Redirect3.Length > 0)
                {
                    foreach (string role in user.Roles)
                    {
                        if (role == settingsHelper.Role3)
                        {
                            Response.Redirect(settingsHelper.Redirect3);
                        }
                    }
                }

                if (settingsHelper.Redirect4.Length > 0)
                {
                    foreach (string role in user.Roles)
                    {
                        if (role == settingsHelper.Role4)
                        {
                            Response.Redirect(settingsHelper.Redirect4);
                        }
                    }
                }

                if (settingsHelper.Redirect5.Length > 0)
                {
                    foreach (string role in user.Roles)
                    {
                        if (role == settingsHelper.Role5)
                        {
                            Response.Redirect(settingsHelper.Redirect5);
                        }
                    }
                }            
            
            Response.Redirect(Request.UrlReferrer.AbsoluteUri);

            
        }
        void Login()
        {

            DebugOutput.Text += "Submit Click";
            string checkbox = (string)Request.Form["DNNspotRememberMe" + ModuleId.ToString()];
            bool rememberme = false;
            if (checkbox == "on")
                rememberme = true;

         UserLoginStatus userloginstatus=UserLogin((string)Request.Form["DNNspotUserName" + ModuleId.ToString()], (string)Request.Form["DNNspotPassword" + ModuleId.ToString()], rememberme);
         if (userloginstatus == UserLoginStatus.LOGIN_SUCCESS || userloginstatus==UserLoginStatus.LOGIN_SUPERUSER)
             RedirectLogin((string)Request.Form["DNNspotUserName" + ModuleId.ToString()]);
         else
             GenerateLogin(GetErrorMessage(userloginstatus));
 
        }

        string GetErrorMessage(UserLoginStatus userloginstatus)
        {
            if (userloginstatus == UserLoginStatus.LOGIN_FAILURE)
                return settingsHelper.FailedLogin;
            else if (userloginstatus == UserLoginStatus.LOGIN_USERLOCKEDOUT)
                return settingsHelper.LockedOut;
            else if (userloginstatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                return settingsHelper.NotApproved;
            else
                return settingsHelper.OtherLoginErrors;

        }

        protected void SubmitLogin_Click(object sender, EventArgs e)
        {
            Login();
       }

        protected void LoginButton_Click(object sender, EventArgs e)
        {
            Login();
        }

        protected void LoginImageButton_Click(object sender, ImageClickEventArgs e)
        {
            Login();
        }

        private void ConfigureDefaults()
        {
            if (Settings["txtLoginTemplate"] != null)
               settingsHelper.LoginTemplate = (string)Settings["txtLoginTemplate"];

            if (Settings["txtLoggedInTemplate"] != null)
                settingsHelper.LoggedInTemplate = (string)Settings["txtLoggedInTemplate"];
            
            if (Settings["txtFailedLogin"] != null)
                settingsHelper.FailedLogin = (string)Settings["txtFailedLogin"];

            if (Settings["txtLockedOut"] != null)
                settingsHelper.LockedOut = (string)Settings["txtLockedOut"];

            if (Settings["txtNotApproved"] != null)
                settingsHelper.NotApproved = (string)Settings["txtNotApproved"];

            if (Settings["txtOtherLoginIssue"] != null)
                settingsHelper.OtherLoginErrors = (string)Settings["txtOtherLoginIssue"];
            if (Settings["txtLoginButtonText"] != null)
                settingsHelper.LoginButtonText = (string)Settings["txtLoginButtonText"];
            if (Settings["txtImageUrl"] != null)
                settingsHelper.LoginButtonImageUrl = (string)Settings["txtImageUrl"];
            if (Settings["txtImageButtonWidth"] != null)
                settingsHelper.LoginButtonImageWidth = Int32.Parse((string)Settings["txtImageButtonWidth"]);
            if (Settings["txtImageButtonHeight"] != null)
                settingsHelper.LoginButtonImageHeight = Int32.Parse((string)Settings["txtImageButtonHeight"]);
            
            if (Settings["drpRoles1"] != null)
                settingsHelper.Role1 = (string)Settings["drpRoles1"];
            if (Settings["txtRedirect1"] != null)
                settingsHelper.Redirect1 = (string)Settings["txtRedirect1"];

            if (Settings["drpRoles2"] != null)
                settingsHelper.Role2 = (string)Settings["drpRoles2"];

            if (Settings["txtRedirect2"] != null)
                settingsHelper.Redirect2 = (string)Settings["txtRedirect2"];

            if (Settings["drpRoles3"] != null)
                settingsHelper.Role3 = (string)Settings["drpRoles3"];
            if (Settings["txtRedirect3"] != null)
                settingsHelper.Redirect3 = (string)Settings["txtRedirect3"];

            if (Settings["drpRoles4"] != null)
                settingsHelper.Role4 = (string)Settings["drpRoles4"];
            if (Settings["txtRedirect4"] != null)
                settingsHelper.Redirect4 = (string)Settings["txtRedirect4"];

            if (Settings["drpRoles5"] != null)
                settingsHelper.Role5 = (string)Settings["drpRoles5"];
            if (Settings["txtRedirect5"] != null)
                settingsHelper.Redirect5 = (string)Settings["txtRedirect5"];


        }

    }
}